package com.maimao.upload.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.maimao.core.constant.ListData;
import com.maimao.core.model.resp.Result;
import com.maimao.upload.client.UserClient;
import com.maimao.upload.config.properties.CacheProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author MaoLin Wang
 * @date 2020/12/17 9:11 下午
 */
@Service
public class UploadCache {
    private CacheProperties cacheProperties;

    private Logger logger = LoggerFactory.getLogger(UploadCache.class);
    @Autowired
    private UserClient userClient;

    /**
     * 会员的三个证件照地址缓存 userId : { "idUrlFront": url, "idUrlBack":url, "idUrlHand":url }
     */
    private final LoadingCache<Long, Optional<Map<String, String>>> memberIdUrl;


    public UploadCache(CacheProperties cacheProperties) {
        this.cacheProperties = cacheProperties;
        memberIdUrl = CacheBuilder.newBuilder()
                .maximumSize(80)
                .expireAfterAccess(cacheProperties.getIdTypeTime(), TimeUnit.MINUTES)
                .recordStats()
                .build(new CacheLoader<Long, Optional<Map<String, String>>>() {
                    @Override
                    public Optional<Map<String, String>> load(Long key) throws Exception {
                        if (key == null || key < 0) {
                            return Optional.of(ListData.EMPTY_MAP);
                        }
                        Result<Map<String, String>> res = userClient.getIdCardUrlByUid(Long.valueOf(key));
                        Map<String, String> data = res.getData();
                        logger.info("get from database  {}",data);
                        if (data != null) {
                            return Optional.of(data);
                        }
                        return Optional.of(ListData.EMPTY_MAP);
                    }
                });
    }

    public LoadingCache<Long, Optional<Map<String, String>>> getMemberIdUrl() {
        return memberIdUrl;
    }

    public void refreshCache(Long key) {
        this.memberIdUrl.refresh(key);
    }

    public void print(Long key) {
        try {
            Map<String, String> stringStringMap = this.memberIdUrl.get(key).get();
            System.out.println(stringStringMap);
            System.out.println("=================");
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
